/**
 * 分析结果管理器
 * 负责管理分析结果查询、展示和相关功能
 */
class AnalysisResultsManager {
    constructor() {
        this.currentTab = 'regional';
        this.currentPage = 1;
        this.pageSize = 10; // 修改默认页面大小为10条
        this.filters = {};
        this.cache = new Map();
        this.isLoading = false;
        
        // 分析类型配置
        this.analysisTypes = {
            'regional': {
                name: '区域分析',
                icon: 'fas fa-map-marker-alt',
                apiType: 'regional',
                // 专属统计指标配置
                statsCards: [
                    {
                        id: 'total_count',
                        title: '总分析数',
                        icon: 'fas fa-map-marked-alt',
                        color: 'blue',
                        bgColor: 'bg-blue-100',
                        textColor: 'text-blue-600',
                        calculation: 'count',
                        field: null,
                        format: 'number'
                    },
                    {
                        id: 'location_rate',
                        title: '定位成功率',
                        icon: 'fas fa-location-arrow',
                        color: 'green',
                        bgColor: 'bg-green-100',
                        textColor: 'text-green-600',
                        calculation: 'percentage',
                        field: 'location_rate',
                        format: 'percentage'
                    },
                    {
                        id: 'region_coverage',
                        title: '区域覆盖率',
                        icon: 'fas fa-globe-asia',
                        color: 'purple',
                        bgColor: 'bg-purple-100',
                        textColor: 'text-purple-600',
                        calculation: 'percentage',
                        field: 'region_coverage',
                        format: 'percentage'
                    },
                    {
                        id: 'avg_confidence',
                        title: '平均置信度',
                        icon: 'fas fa-percentage',
                        color: 'yellow',
                        bgColor: 'bg-yellow-100',
                        textColor: 'text-yellow-600',
                        calculation: 'average',
                        field: 'avg_confidence',
                        format: 'percentage'
                    }
                ],
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '8%' },
                    { key: 'tsr', label: '投诉人', width: '8%' },
                    { key: 'xfnr', label: '信访内容', width: '42%', truncate: true },
                    { key: 'dzxx_xzq', label: '区域', width: '8%' },
                    { key: 'dzxx_jd', label: '街道', width: '8%' },
                    { key: 'confidence', label: '置信度', width: '8%' },
                    { key: 'created_at', label: '分析时间', width: '10%' },
                    { key: 'actions', label: '操作', width: '8%' }
                ]
            },
            'complaint-type': {
                name: '投诉类型分析',
                icon: 'fas fa-tags',
                apiType: 'complaint-types',
                // 专属统计指标配置
                statsCards: [
                    {
                        id: 'total_count',
                        title: '总分析数',
                        icon: 'fas fa-clipboard-list',
                        color: 'blue',
                        bgColor: 'bg-blue-100',
                        textColor: 'text-blue-600',
                        calculation: 'count',
                        field: null,
                        format: 'number'
                    },
                    {
                        id: 'type_coverage',
                        title: '类型覆盖率',
                        icon: 'fas fa-tags',
                        color: 'green',
                        bgColor: 'bg-green-100',
                        textColor: 'text-green-600',
                        calculation: 'percentage',
                        field: 'type_coverage',
                        format: 'percentage'
                    },
                    {
                        id: 'main_type_ratio',
                        title: '主要类型占比',
                        icon: 'fas fa-chart-pie',
                        color: 'purple',
                        bgColor: 'bg-purple-100',
                        textColor: 'text-purple-600',
                        calculation: 'percentage',
                        field: 'main_type_ratio',
                        format: 'percentage'
                    },
                    {
                        id: 'avg_confidence',
                        title: '平均置信度',
                        icon: 'fas fa-percentage',
                        color: 'yellow',
                        bgColor: 'bg-yellow-100',
                        textColor: 'text-yellow-600',
                        calculation: 'average',
                        field: 'avg_confidence',
                        format: 'percentage'
                    }
                ],
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '8%' },
                    { key: 'xfnr', label: '信访内容', width: '45%', truncate: true },
                    { key: 'full_complaint_type', label: '投诉类型', width: '22%', truncate: true },
                    { key: 'level2_confidence', label: '二级置信度', width: '8%' },
                    { key: 'level3_confidence', label: '三级置信度', width: '8%' },
                    { key: 'created_at', label: '分析时间', width: '6%' },
                    { key: 'actions', label: '操作', width: '3%' }
                ]
            },
            'sentiment': {
                name: '情感分析',
                icon: 'fas fa-heart',
                apiType: 'sentiment',
                // 专属统计指标配置
                statsCards: [
                    {
                        id: 'total_count',
                        title: '总分析数',
                        icon: 'fas fa-heart',
                        color: 'blue',
                        bgColor: 'bg-blue-100',
                        textColor: 'text-blue-600',
                        calculation: 'count',
                        field: null,
                        format: 'number'
                    },
                    {
                        id: 'sentiment_distribution',
                        title: '情感分布率',
                        icon: 'fas fa-chart-pie',
                        color: 'green',
                        bgColor: 'bg-green-100',
                        textColor: 'text-green-600',
                        calculation: 'percentage',
                        field: 'sentiment_distribution',
                        format: 'percentage'
                    },
                    {
                        id: 'negative_sentiment_rate',
                        title: '负面情绪占比',
                        icon: 'fas fa-exclamation-triangle',
                        color: 'red',
                        bgColor: 'bg-red-100',
                        textColor: 'text-red-600',
                        calculation: 'percentage',
                        field: 'negative_sentiment_rate',
                        format: 'percentage'
                    },
                    {
                        id: 'avg_sentiment_intensity',
                        title: '平均情感强度',
                        icon: 'fas fa-tachometer-alt',
                        color: 'yellow',
                        bgColor: 'bg-yellow-100',
                        textColor: 'text-yellow-600',
                        calculation: 'average',
                        field: 'avg_sentiment_intensity',
                        format: 'number'
                    }
                ],
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '12%' },
                    { key: 'xfnr', label: '信访内容', width: '30%', truncate: true },
                    { key: 'sentiment_level', label: '情感类型', width: '12%' },
                    { key: 'qgfx_zy', label: '摘要', width: '20%', truncate: true },
                    { key: 'keywords_list', label: '关键词', width: '10%' },
                    { key: 'created_at', label: '分析时间', width: '12%' },
                    { key: 'actions', label: '操作', width: '4%' }
                ]
            },
            'compliance': {
                name: '规范性分析',
                icon: 'fas fa-check-circle',
                apiType: 'compliance',
                // 专属统计指标配置
                statsCards: [
                    {
                        id: 'total_count',
                        title: '总分析数',
                        icon: 'fas fa-clipboard-check',
                        color: 'blue',
                        bgColor: 'bg-blue-100',
                        textColor: 'text-blue-600',
                        calculation: 'count',
                        field: null,
                        format: 'number'
                    },
                    {
                        id: 'compliance_rate',
                        title: '合规率',
                        icon: 'fas fa-check-double',
                        color: 'green',
                        bgColor: 'bg-green-100',
                        textColor: 'text-green-600',
                        calculation: 'percentage',
                        field: 'compliance_rate',
                        format: 'percentage'
                    },
                    {
                        id: 'department_compliance',
                        title: '部门合规率',
                        icon: 'fas fa-building',
                        color: 'purple',
                        bgColor: 'bg-purple-100',
                        textColor: 'text-purple-600',
                        calculation: 'percentage',
                        field: 'department_compliance',
                        format: 'percentage'
                    },
                    {
                        id: 'violation_types',
                        title: '违规类型数',
                        icon: 'fas fa-exclamation-circle',
                        color: 'yellow',
                        bgColor: 'bg-yellow-100',
                        textColor: 'text-yellow-600',
                        calculation: 'count',
                        field: 'violation_types',
                        format: 'number'
                    }
                ],
                columns: [
                    { key: 'petition_record_id', label: '信访编号', width: '12%' },
                    { key: 'xfnr', label: '信访内容', width: '30%', truncate: true },
                    { key: 'gffx_dfnr', label: '答复内容', width: '20%', truncate: true },
                    { key: 'compliance_status', label: '合规状态', width: '12%' },
                    { key: 'gffx_pdly', label: '判断理由', width: '12%', truncate: true },
                    { key: 'created_at', label: '分析时间', width: '10%' },
                    { key: 'actions', label: '操作', width: '4%' }
                ]
            },
            'duplicate': {
                name: '重复分析',
                icon: 'fas fa-copy',
                apiType: 'duplicate',
                // 专属统计指标配置
                statsCards: [
                    {
                        id: 'total_count',
                        title: '总分析数',
                        icon: 'fas fa-copy',
                        color: 'blue',
                        bgColor: 'bg-blue-100',
                        textColor: 'text-blue-600',
                        calculation: 'count',
                        field: null,
                        format: 'number'
                    },
                    {
                        id: 'duplicate_rate',
                        title: '重复率',
                        icon: 'fas fa-percentage',
                        color: 'red',
                        bgColor: 'bg-red-100',
                        textColor: 'text-red-600',
                        calculation: 'percentage',
                        field: 'duplicate_rate',
                        format: 'percentage'
                    },
                    {
                        id: 'duplicate_groups',
                        title: '重复组数',
                        icon: 'fas fa-layer-group',
                        color: 'purple',
                        bgColor: 'bg-purple-100',
                        textColor: 'text-purple-600',
                        calculation: 'count',
                        field: 'duplicate_groups',
                        format: 'number'
                    },
                    {
                        id: 'high_freq_duplicates',
                        title: '高频重复问题',
                        icon: 'fas fa-exclamation',
                        color: 'yellow',
                        bgColor: 'bg-yellow-100',
                        textColor: 'text-yellow-600',
                        calculation: 'count',
                        field: 'high_freq_duplicates',
                        format: 'number'
                    }
                ],
                columns: [
                    { key: 'cfbh', label: '重复组编号', width: '15%' },
                    { key: 'xfxh', label: '信访编号', width: '15%' },
                    { key: 'petition_record', label: '信访信息', width: '40%' },
                    { key: 'task_id', label: '任务ID', width: '10%' },
                    { key: 'created_at', label: '分析时间', width: '14%' },
                    { key: 'actions', label: '操作', width: '6%' }
                ]
            }
        };
        
        this.init();
    }
    
    /**
     * 初始化管理器
     */
    init() {
        console.log('分析结果管理器初始化...');
        this.bindEvents();
        this.loadInitialData();
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        // Tab切换事件
        const tabs = document.querySelectorAll('.analysis-tab');
        console.log('找到Tab数量:', tabs.length);
        
        tabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                const tabType = e.currentTarget.getAttribute('data-tab');
                console.log('Tab被点击:', tabType);
                this.switchTab(tabType);
            });
        });
        
          
        // 导出和刷新按钮
        document.getElementById('exportResultsBtn')?.addEventListener('click', () => {
            this.exportResults();
        });
        
        document.getElementById('refreshResultsBtn')?.addEventListener('click', () => {
            this.refreshResults();
        });
        
        // 过滤器事件
        document.getElementById('taskFilter')?.addEventListener('change', () => {
            this.applyFilters();
        });
        
        document.getElementById('districtFilter')?.addEventListener('change', () => {
            this.loadStreetOptions();
        });
        
        document.getElementById('streetFilter')?.addEventListener('change', () => {
            this.applyFilters();
        });
        
        document.getElementById('typeFilter')?.addEventListener('change', () => {
            this.applyFilters();
        });
        
        document.getElementById('startDateFilter')?.addEventListener('change', () => {
            this.applyFilters();
        });
        
        document.getElementById('endDateFilter')?.addEventListener('change', () => {
            this.applyFilters();
        });
        
        // 监听Enter键搜索
        document.getElementById('searchInput')?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.applyFilters();
            }
        });
        
        // 重置按钮
        document.getElementById('resetFiltersBtn')?.addEventListener('click', () => {
            this.resetFilters();
        });
        
        // 模态框关闭按钮
        document.getElementById('closeDetailModalBtn1')?.addEventListener('click', () => {
            this.closeDetailModal();
        });
        
        document.getElementById('closeDetailModalBtn2')?.addEventListener('click', () => {
            this.closeDetailModal();
        });
        
        // 模态框外部点击关闭
        document.getElementById('resultDetailModal')?.addEventListener('click', (e) => {
            if (e.target.id === 'resultDetailModal') {
                this.closeDetailModal();
            }
        });
        
        // 页面大小选择器事件
        document.getElementById('pageSizeSelect')?.addEventListener('change', (e) => {
            this.changePageSize(parseInt(e.target.value));
        });

        // 使用事件委托处理动态生成的按钮
        document.addEventListener('click', (e) => {
            // 处理详情按钮
            if (e.target.closest('.detail-btn')) {
                const id = e.target.closest('.detail-btn').getAttribute('data-id');
                this.showDetail(id);
            }

            // 处理分页按钮
            if (e.target.closest('.pagination-btn')) {
                const page = parseInt(e.target.closest('.pagination-btn').getAttribute('data-page'));
                if (page && !e.target.closest('.pagination-btn').hasAttribute('disabled')) {
                    this.goToPage(page);
                }
            }
        });
    }
    
    /**
     * 加载初始数据
     */
    async loadInitialData() {
        try {
            await this.loadTaskOptions();
            await this.loadRegionOptions();
            await this.loadTypeOptions();
            await this.loadDashboardStats();
            await this.loadResults();
        } catch (error) {
            console.error('加载初始数据失败:', error);
            this.showError('加载数据失败，请刷新页面重试');
        }
    }
    
    /**
     * 切换Tab
     */
    async switchTab(tabType) {
        console.log('切换Tab:', tabType, '当前:', this.currentTab);
        
        if (this.currentTab === tabType) return;
        
        // 更新Tab状态
        document.querySelectorAll('.analysis-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        
        const targetTab = document.querySelector(`[data-tab="${tabType}"]`);
        if (targetTab) {
            targetTab.classList.add('active');
        } else {
            console.error('找不到目标Tab:', tabType);
            return;
        }
        
        this.currentTab = tabType;
        this.currentPage = 1;
        this.filters = {};

        // 清空现有选项，避免重复
        this.clearAllFilters();

        // 重新加载数据
        await this.loadInitialData();
    }
    
    /**
     * 加载任务选项
     */
    async loadTaskOptions() {
        try {
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=${this.currentTab}&option_type=tasks`);
            const result = await response.json();
            console.log('任务选项响应:', result);
            
            if (response.status === 200) {
                const select = document.getElementById('taskFilter');
                select.innerHTML = '<option value="">全部任务</option>';
                
                // API直接返回数组
                result.forEach(task => {
                    const option = document.createElement('option');
                    option.value = task.value;
                    option.textContent = task.label;
                    select.appendChild(option);
                });
            }
        } catch (error) {
            console.error('加载任务选项失败:', error);
        }
    }
    
    /**
     * 加载区域选项
     */
    async loadRegionOptions() {
        try {
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=${this.currentTab}&option_type=regions`);
            const result = await response.json();
            console.log('区域选项响应:', result);
            
            if (response.status === 200) {
                const districtSelect = document.getElementById('districtFilter');
                const streetSelect = document.getElementById('streetFilter');
                
                districtSelect.innerHTML = '<option value="">全部区县</option>';
                streetSelect.innerHTML = '<option value="">全部街道</option>';
                
                // API直接返回对象
                result.districts.forEach(district => {
                    const option = document.createElement('option');
                    option.value = district;
                    option.textContent = district;
                    districtSelect.appendChild(option);
                });
                
                // 保存街道数据用于级联选择
                this.streetData = result.streets || {};
            }
        } catch (error) {
            console.error('加载区域选项失败:', error);
        }
    }
    
    /**
     * 加载街道选项（级联）
     */
    async loadStreetOptions() {
        const districtSelect = document.getElementById('districtFilter');
        const streetSelect = document.getElementById('streetFilter');
        const selectedDistrict = districtSelect.value;
        
        streetSelect.innerHTML = '<option value="">全部街道</option>';
        
        if (selectedDistrict && this.streetData[selectedDistrict]) {
            this.streetData[selectedDistrict].forEach(street => {
                const option = document.createElement('option');
                option.value = street;
                option.textContent = street;
                streetSelect.appendChild(option);
            });
        }
        
        this.applyFilters();
    }
    
    /**
     * 加载类型选项
     */
    async loadTypeOptions() {
        try {
            const response = await fetch(`/api/analysis-results-new/options/?analysis_type=${this.currentTab}&option_type=types`);
            const result = await response.json();
            console.log('类型选项响应:', result);
            
            if (response.status === 200) {
                const typeSelect = document.getElementById('typeFilter');
                typeSelect.innerHTML = '<option value="">全部类型</option>';
                
                if (this.currentTab === 'complaint-type') {
                    // 投诉类型特殊处理
                    result.level1.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type;
                        option.textContent = type;
                        typeSelect.appendChild(option);
                    });
                } else if (this.currentTab === 'sentiment') {
                    // 情感类型
                    result.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type;
                        option.textContent = type;
                        typeSelect.appendChild(option);
                    });
                } else if (this.currentTab === 'compliance') {
                    // 合规状态
                    result.forEach(type => {
                        const option = document.createElement('option');
                        option.value = type.value;
                        option.textContent = type.label;
                        typeSelect.appendChild(option);
                    });
                }
            }
        } catch (error) {
            console.error('加载类型选项失败:', error);
        }
    }
    
    /**
     * 加载仪表板统计数据
     */
    async loadDashboardStats() {
        try {
            const response = await fetch(`/api/analysis-results-new/dashboard-stats/?analysis_type=${this.currentTab}`);
            const result = await response.json();
            console.log('仪表板统计数据响应:', result);
            
            if (response.status === 200) {
                // API直接返回统计数据对象，没有包装在data字段中
                const stats = result;
                this.renderDynamicStatsCards(stats);
            } else {
                console.error('加载统计数据失败:', result.message || '未知错误');
                this.showError('加载统计数据失败');
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
            this.showError('统计数据加载异常');
        }
    }

    /**
     * 动态渲染统计卡片
     */
    renderDynamicStatsCards(stats) {
        const currentConfig = this.analysisTypes[this.currentTab];
        if (!currentConfig || !currentConfig.statsCards) {
            console.warn('未找到当前分析类型的统计卡片配置');
            return;
        }

        const container = document.querySelector('.grid.grid-cols-1.md\\:grid-cols-4.gap-4');
        if (!container) {
            console.warn('未找到统计卡片容器');
            return;
        }

        // 清空现有卡片
        container.innerHTML = '';

        // 渲染新的统计卡片
        currentConfig.statsCards.forEach(cardConfig => {
            const cardElement = this.createStatsCard(cardConfig, stats);
            container.appendChild(cardElement);
        });

        console.log(`已渲染 ${currentConfig.statsCards.length} 个统计卡片`);
    }

    /**
     * 创建单个统计卡片元素
     */
    createStatsCard(cardConfig, stats) {
        const card = document.createElement('div');
        card.className = 'bg-white rounded-lg border border-slate-200 p-4 transition-all duration-300 hover:shadow-md';
        
        // 获取统计值
        let value = this.getStatValue(cardConfig, stats);
        
        // 格式化显示值
        const formattedValue = this.formatStatValue(value, cardConfig.format);
        
        card.innerHTML = `
            <div class="flex items-center justify-between">
                <div class="flex-1">
                    <p class="text-sm text-slate-600 mb-1">${cardConfig.title}</p>
                    <p class="text-2xl font-bold text-slate-800">${formattedValue}</p>
                    ${this.renderTrendIndicator(cardConfig, stats)}
                </div>
                <div class="w-12 h-12 ${cardConfig.bgColor} rounded-lg flex items-center justify-center ml-4">
                    <i class="${cardConfig.icon} ${cardConfig.textColor}"></i>
                </div>
            </div>
        `;

        // 添加点击事件（如果有需要）
        if (cardConfig.onClick) {
            card.style.cursor = 'pointer';
            card.addEventListener('click', () => cardConfig.onClick(stats));
        }

        return card;
    }

    /**
     * 获取统计值
     */
    getStatValue(cardConfig, stats) {
        const { field, calculation } = cardConfig;
        
        if (field && stats[field] !== undefined) {
            return stats[field];
        }
        
        // 根据计算类型获取值
        switch (calculation) {
            case 'count':
                return stats.total || 0;
            case 'percentage':
                return stats[field] || 0;
            case 'average':
                return stats[field] || 0;
            default:
                return 0;
        }
    }

    /**
     * 格式化统计值
     */
    formatStatValue(value, format) {
        if (value === null || value === undefined) {
            return '0';
        }

        switch (format) {
            case 'number':
                return Number(value).toLocaleString();
            case 'percentage':
                return `${Number(value).toFixed(1)}%`;
            case 'decimal':
                return Number(value).toFixed(2);
            default:
                return value.toString();
        }
    }

    /**
     * 渲染趋势指示器（可选功能）
     */
    renderTrendIndicator(cardConfig, stats) {
        // 这里可以添加趋势变化的逻辑
        // 暂时返回空字符串，后续可以扩展
        return '';
    }
    
    /**
     * 应用过滤器
     */
    applyFilters() {
        this.currentPage = 1;
        this.filters = this.getFilterValues();
        this.loadResults();
    }
    
    /**
     * 获取过滤器值
     */
    getFilterValues() {
        return {
            task_id: document.getElementById('taskFilter').value || null,
            district: document.getElementById('districtFilter').value || null,
            street: document.getElementById('streetFilter').value || null,
            type_filter: document.getElementById('typeFilter').value || null,
            start_date: document.getElementById('startDateFilter').value || null,
            end_date: document.getElementById('endDateFilter').value || null,
            search: document.getElementById('searchInput').value || null
        };
    }

    /**
     * 清空所有过滤器选项（用于Tab切换时避免重复）
     */
    clearAllFilters() {
        // 清空选择器的选项，只保留默认选项
        const taskFilter = document.getElementById('taskFilter');
        const districtFilter = document.getElementById('districtFilter');
        const streetFilter = document.getElementById('streetFilter');
        const typeFilter = document.getElementById('typeFilter');

        if (taskFilter) {
            taskFilter.innerHTML = '<option value="">全部任务</option>';
        }
        if (districtFilter) {
            districtFilter.innerHTML = '<option value="">全部区县</option>';
        }
        if (streetFilter) {
            streetFilter.innerHTML = '<option value="">全部街道</option>';
        }
        if (typeFilter) {
            typeFilter.innerHTML = '<option value="">全部类型</option>';
        }

        // 清空街道数据缓存
        this.streetData = {};
    }

    /**
     * 重置过滤器
     */
    resetFilters() {
        document.getElementById('taskFilter').value = '';
        document.getElementById('districtFilter').value = '';
        document.getElementById('streetFilter').value = '';
        document.getElementById('typeFilter').value = '';
        document.getElementById('startDateFilter').value = '';
        document.getElementById('endDateFilter').value = '';
        document.getElementById('searchInput').value = '';
        
        this.filters = {};
        this.currentPage = 1;
        this.loadResults();
    }
    
    /**
     * 加载分析结果
     */
    async loadResults() {
        if (this.isLoading) return;
        
        this.showLoading(true);
        
        try {
            // 构建查询参数
            const params = new URLSearchParams({
                analysis_type: this.currentTab,
                page: this.currentPage,
                page_size: this.pageSize
            });
            
            // 添加过滤器参数
            Object.entries(this.filters).forEach(([key, value]) => {
                if (value !== null && value !== '') {
                    params.append(key, value);
                }
            });
            
            // 检查缓存
            const cacheKey = params.toString();
            if (this.cache.has(cacheKey)) {
                const cachedData = this.cache.get(cacheKey);
                this.renderResults(cachedData);
                this.showLoading(false);
                return;
            }
            
            const response = await fetch(`/api/analysis-results-new/unified/?${params}`);
            const result = await response.json();
            console.log('加载分析结果响应:', result);
            
            if (response.status === 200) {
                // 缓存结果（API返回的数据包装在data字段中）
                this.cache.set(cacheKey, result.data);
                this.renderResults(result.data);
            } else {
                this.showError(result.message || '加载数据失败');
            }
        } catch (error) {
            console.error('加载分析结果失败:', error);
            this.showError('网络错误，请稍后重试');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 渲染结果
     */
    renderResults(data) {
        const container = document.getElementById('resultsTableContainer');
        
        if (data.total === 0) {
            this.showEmptyState();
            return;
        }
        
        // 渲染表格头部
        this.renderTableHeader();
        
        // 渲染表格数据
        this.renderTableBody(data.items);
        
        // 渲染分页
        this.renderPagination(data);
        
        // 显示表格区域
        document.getElementById('resultsTableArea').classList.remove('hidden');
        document.getElementById('resultsPagination').classList.remove('hidden');
        document.getElementById('resultsEmptyState').classList.add('hidden');
    }
    
    /**
     * 渲染表格头部
     */
    renderTableHeader() {
        const header = document.getElementById('resultsTableHeader');
        const columns = this.analysisTypes[this.currentTab].columns;
        
        header.innerHTML = columns.map(col => 
            `<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider" style="width: ${col.width || 'auto'}">
                ${col.label}
            </th>`
        ).join('');
    }
    
    /**
     * 渲染表格数据
     */
    renderTableBody(items) {
        const tbody = document.getElementById('resultsTableBody');
        const columns = this.analysisTypes[this.currentTab].columns;

        // 检查items是否存在且为数组
        if (!items || !Array.isArray(items)) {
            console.error('renderTableBody: items不是有效的数组', items);
            tbody.innerHTML = '<tr><td colspan="100%" class="text-center py-4 text-red-500">数据格式错误</td></tr>';
            return;
        }

        tbody.innerHTML = items.map(item => {
            // 检查item是否存在
            if (!item) {
                console.error('renderTableBody: 发现空的item');
                return '<tr><td colspan="100%" class="text-center py-4 text-red-500">数据项为空</td></tr>';
            }

            const row = columns.map(col => {
                let value = item[col.key] || '';
                let cellClass = 'px-6 py-4 text-sm text-slate-900';

                // 特殊处理某些字段 - 让CSS来处理截断
                if (col.truncate) {
                    cellClass += ' truncate-cell'; // 使用truncate-cell类而不是truncate-text
                    // 添加调试信息
                    console.log(`应用truncate-cell类到列: ${col.key}, 值: ${value.substring(0, 50)}...`);
                    // 不在JavaScript层面截断内容，让CSS根据单元格宽度自动处理
                } else {
                    cellClass += ' whitespace-nowrap';
                }

                if (col.key === 'actions') {
                    return `<td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                        <button class="detail-btn text-indigo-600 hover:text-indigo-900 mr-3" data-id="${item.id}">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                    </td>`;
                }

                if (col.key === 'confidence') {
                    value = value !== undefined && value !== null ? `${Math.round(value * 100)}%` : '0%';
                }

                if (col.key === 'level2_confidence' || col.key === 'level3_confidence') {
                    value = value !== undefined && value !== null ? `${Math.round(value * 100)}%` : '0%';
                }

                if (col.key === 'created_at') {
                    value = value ? new Date(value).toLocaleString('zh-CN') : '';
                }

                if (col.key === 'keywords_list') {
                    value = Array.isArray(value) ? value.slice(0, 3).join(', ') : '';
                }

                // 如果需要截断，添加title属性以便鼠标悬停时显示完整内容
                const titleAttr = col.truncate && item[col.key] ? `title="${item[col.key]}"` : '';
                // 移除内联样式，让CSS控制宽度
                return `<td class="${cellClass}" ${titleAttr}>${value}</td>`;
            }).join('');

            return `<tr class="hover:bg-slate-50">${row}</tr>`;
        }).join('');
    }
    
    /**
     * 渲染分页
     */
    renderPagination(data) {
        const container = document.getElementById('paginationContainer');
        const totalPages = data.total_pages;
        const currentPage = data.page;

        // 更新分页信息
        const startItem = ((currentPage - 1) * this.pageSize + 1);
        const endItem = Math.min(currentPage * this.pageSize, data.total);

        document.getElementById('pageStart').textContent = startItem;
        document.getElementById('pageEnd').textContent = endItem;
        document.getElementById('totalItems').textContent = data.total;

        // 更新页面大小选择器的值
        const pageSizeSelect = document.getElementById('pageSizeSelect');
        if (pageSizeSelect) {
            pageSizeSelect.value = this.pageSize;
        }

        // 如果没有数据或只有一页，隐藏分页按钮
        if (totalPages <= 1) {
            container.innerHTML = '';
            return;
        }

        // 生成分页按钮
        let paginationHTML = '';

        // 上一页
        paginationHTML += `
            <button class="page-btn pagination-btn px-3 py-2 rounded-lg ${currentPage === 1 ? 'disabled' : ''}"
                    data-page="${currentPage - 1}" ${currentPage === 1 ? 'disabled' : ''}
                    title="上一页">
                <i class="fas fa-chevron-left"></i>
            </button>
        `;

        // 页码按钮 - 响应式布局
        const maxVisiblePages = window.innerWidth < 768 ? 3 : 5;
        const startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        const endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        // 调整起始页码确保显示最大页码数
        const adjustedStartPage = Math.max(1, endPage - maxVisiblePages + 1);

        if (adjustedStartPage > 1) {
            paginationHTML += `<button class="page-btn pagination-btn px-3 py-2 rounded-lg" data-page="1" title="第1页">1</button>`;
            if (adjustedStartPage > 2) {
                paginationHTML += `<span class="px-2 text-slate-400">...</span>`;
            }
        }

        for (let i = adjustedStartPage; i <= endPage; i++) {
            paginationHTML += `
                <button class="page-btn pagination-btn px-3 py-2 rounded-lg ${i === currentPage ? 'active' : ''}"
                        data-page="${i}" title="第${i}页">
                    ${i}
                </button>
            `;
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHTML += `<span class="px-2 text-slate-400">...</span>`;
            }
            paginationHTML += `<button class="page-btn pagination-btn px-3 py-2 rounded-lg" data-page="${totalPages}" title="第${totalPages}页">${totalPages}</button>`;
        }

        // 下一页
        paginationHTML += `
            <button class="page-btn pagination-btn px-3 py-2 rounded-lg ${currentPage === totalPages ? 'disabled' : ''}"
                    data-page="${currentPage + 1}" ${currentPage === totalPages ? 'disabled' : ''}
                    title="下一页">
                <i class="fas fa-chevron-right"></i>
            </button>
        `;

        container.innerHTML = paginationHTML;
    }
    
    /**
     * 跳转到指定页
     */
    goToPage(page) {
        if (page < 1) return;
        this.currentPage = page;
        this.loadResults();
    }
    
    /**
     * 显示详情 - 支持5种分析类型的详情展示
     */
    async showDetail(id) {
        try {
            console.log('显示详情:', id, '当前分析类型:', this.currentTab);

            // 验证输入参数
            if (!id || id === 'undefined' || id === 'null') {
                this.renderErrorDetail('无效的记录ID');
                return;
            }

            // 检查当前分析类型是否有效
            if (!this.analysisTypes[this.currentTab]) {
                this.renderErrorDetail('无效的分析类型');
                return;
            }

            // 显示加载状态
            this.showModalLoading(true);

            // 显示模态框
            const modal = document.getElementById('resultDetailModal');
            const content = document.getElementById('resultDetailContent');
            if (!modal || !content) {
                console.error('模态框元素不存在');
                this.showError('页面元素加载失败，请刷新页面');
                return;
            }

            modal.classList.remove('hidden');
            modal.classList.add('flex');

            // 添加键盘事件监听
            this.addKeyboardEventListeners();

            // 根据分析类型获取详情数据
            const detailData = await this.fetchDetailData(id);

            if (detailData) {
                // 验证数据完整性
                if (!this.validateDetailData(detailData)) {
                    this.renderErrorDetail('数据格式错误或缺少必要字段');
                    return;
                }

                // 根据当前分析类型渲染不同的详情内容
                switch (this.currentTab) {
                    case 'regional':
                        this.renderRegionalDetail(detailData);
                        break;
                    case 'complaint-type':
                        this.renderComplaintTypeDetail(detailData);
                        break;
                    case 'sentiment':
                        this.renderSentimentDetail(detailData);
                        break;
                    case 'compliance':
                        this.renderComplianceDetail(detailData);
                        break;
                    case 'duplicate':
                        this.renderDuplicateDetail(detailData);
                        break;
                    default:
                        this.renderErrorDetail('未知的分析类型');
                }
            } else {
                this.renderErrorDetail('获取详情数据失败');
            }

        } catch (error) {
            console.error('显示详情失败:', error);
            this.renderErrorDetail('加载详情失败: ' + error.message);
        } finally {
            this.showModalLoading(false);
        }
    }
    
    /**
     * 验证详情数据完整性
     */
    validateDetailData(data) {
        if (!data || typeof data !== 'object') {
            return false;
        }

        // 根据分析类型验证必要字段
        switch (this.currentTab) {
            case 'regional':
                return data.petition_record_id !== undefined;
            case 'complaint-type':
                return data.petition_record_id !== undefined && data.xfnr !== undefined;
            case 'sentiment':
                return data.petition_record_id !== undefined && data.xfnr !== undefined;
            case 'compliance':
                return data.petition_record_id !== undefined;
            case 'duplicate':
                return data.cfbh !== undefined;
            default:
                return false;
        }
    }

    /**
     * 添加键盘事件监听
     */
    addKeyboardEventListeners() {
        // ESC键关闭模态框
        const handleEscape = (e) => {
            if (e.key === 'Escape') {
                this.closeDetailModal();
                document.removeEventListener('keydown', handleEscape);
            }
        };

        document.addEventListener('keydown', handleEscape);

        // 确保在模态框关闭时移除事件监听
        const modal = document.getElementById('resultDetailModal');
        if (modal) {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.closeDetailModal();
                    document.removeEventListener('keydown', handleEscape);
                }
            });
        }
    }

    /**
     * 获取详情数据
     */
    async fetchDetailData(id) {
        try {
            const apiType = this.analysisTypes[this.currentTab].apiType;
            const apiUrl = `/api/analysis-results-new/${apiType}/${id}/`;

            console.log('获取详情数据，API URL:', apiUrl);

            const response = await fetch(apiUrl);

            if (response.status === 200) {
                const responseData = await response.json();
                console.log('获取详情数据成功:', responseData);
                // API返回格式为 {code: 200, message: success, data: Object, timestamp: ...}
                // 需要返回其中的data字段
                if (responseData.code === 200 && responseData.data) {
                    return responseData.data;
                } else {
                    console.error('API响应格式错误:', responseData);
                    return null;
                }
            } else if (response.status === 404) {
                console.error('详情数据不存在:', response.status);
                return null;
            } else {
                console.error('获取详情数据失败:', response.status);
                const errorText = await response.text();
                console.error('错误响应:', errorText);
                return null;
            }
        } catch (error) {
            console.error('获取详情数据异常:', error);
            return null;
        }
    }

    /**
     * 显示模态框加载状态
     */
    showModalLoading(show) {
        const content = document.getElementById('resultDetailContent');
        if (show) {
            content.innerHTML = `
                <div class="flex items-center justify-center py-12">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
                    <span class="ml-3 text-slate-600">正在加载详情...</span>
                </div>
            `;
        }
    }

    /**
     * 渲染错误状态
     */
    renderErrorDetail(message) {
        const content = document.getElementById('resultDetailContent');
        content.innerHTML = `
            <div class="text-center py-12">
                <i class="fas fa-exclamation-triangle text-4xl text-red-400 mb-4"></i>
                <p class="text-red-600 text-lg">${message}</p>
                <button onclick="analysisResultsManager.closeDetailModal()"
                        class="mt-4 px-4 py-2 bg-slate-200 text-slate-700 rounded-lg hover:bg-slate-300">
                    关闭
                </button>
            </div>
        `;
    }

    /**
     * 渲染区域分析详情
     */
    renderRegionalDetail(data) {
        const content = document.getElementById('resultDetailContent');
        const hasLocation = data.has_location || false;
        const locationCoordinates = data.location_coordinates || [null, null];

        content.innerHTML = `
            <!-- 基本信息 -->
            <div class="space-y-6">
                <div class="bg-blue-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-blue-800 mb-3">
                        <i class="fas fa-map-marker-alt mr-2"></i>区域分析详情
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-blue-600">信访编号</p>
                            <p class="font-medium text-blue-900">${data.petition_record_id || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-blue-600">投诉人</p>
                            <p class="font-medium text-blue-900">${data.tsr || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-blue-600">置信度</p>
                            <p class="font-medium text-blue-900">${this.formatConfidence(data.confidence_score)}</p>
                        </div>
                        <div>
                            <p class="text-sm text-blue-600">分析时间</p>
                            <p class="font-medium text-blue-900">${this.formatDateTime(data.created_at)}</p>
                        </div>
                    </div>
                </div>

                <!-- 地理位置信息 -->
                <div class="bg-green-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-green-800 mb-3">
                        <i class="fas fa-globe mr-2"></i>地理位置信息
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-green-600">行政区</p>
                            <p class="font-medium text-green-900">${data.dzxx_xzq || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-green-600">街道</p>
                            <p class="font-medium text-green-900">${data.dzxx_jd || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-green-600">投诉对象</p>
                            <p class="font-medium text-green-900">${data.dzxx_tsdx || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-green-600">投诉地址</p>
                            <p class="font-medium text-green-900">${data.dzxx_tsdz || '未知'}</p>
                        </div>
                        ${hasLocation ? `
                        <div>
                            <p class="text-sm text-green-600">经度</p>
                            <p class="font-medium text-green-900">${locationCoordinates[0] || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-green-600">纬度</p>
                            <p class="font-medium text-green-900">${locationCoordinates[1] || '未知'}</p>
                        </div>
                        ` : ''}
                    </div>
                </div>

                <!-- 地图可视化 -->
                ${hasLocation ? `
                <div class="bg-yellow-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-yellow-800 mb-3">
                        <i class="fas fa-map mr-2"></i>位置地图
                    </h4>
                    <div id="detailMap" class="h-64 bg-yellow-100 rounded-lg flex items-center justify-center">
                        <div class="text-center">
                            <i class="fas fa-map-marked-alt text-2xl text-yellow-600 mb-2"></i>
                            <p class="text-yellow-700">地图加载中...</p>
                        </div>
                    </div>
                </div>
                ` : ''}

                <!-- 信访内容 -->
                <div class="bg-purple-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-purple-800 mb-3">
                        <i class="fas fa-file-alt mr-2"></i>信访内容
                    </h4>
                    <div class="bg-white rounded-lg p-3 max-h-32 overflow-y-auto">
                        <p class="text-slate-700 whitespace-pre-wrap">${data.xfnr || '无内容'}</p>
                    </div>
                </div>

                <!-- 辅助信息 -->
                <div class="bg-slate-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-slate-800 mb-3">
                        <i class="fas fa-info-circle mr-2"></i>辅助信息
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-slate-600">投诉对象关键词</p>
                            <p class="font-medium text-slate-900">${data.dzxx_dx_words || '无'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">投诉地址关键词</p>
                            <p class="font-medium text-slate-900">${data.dzxx_dz_words || '无'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">重复编号</p>
                            <p class="font-medium text-slate-900">${data.cfxs_bh || '无'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">重复概率</p>
                            <p class="font-medium text-slate-900">${this.formatConfidence(data.confidence_score)}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 如果有位置信息，加载地图
        if (hasLocation && locationCoordinates[0] && locationCoordinates[1]) {
            setTimeout(() => {
                this.loadDetailMap(locationCoordinates[0], locationCoordinates[1]);
            }, 100);
        }
    }

    /**
     * 渲染投诉类型分析详情
     */
    renderComplaintTypeDetail(data) {
        const content = document.getElementById('resultDetailContent');

        content.innerHTML = `
            <!-- 基本信息 -->
            <div class="space-y-6">
                <div class="bg-indigo-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-indigo-800 mb-3">
                        <i class="fas fa-tags mr-2"></i>投诉类型分析详情
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-indigo-600">信访编号</p>
                            <p class="font-medium text-indigo-900">${data.petition_record_id || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-indigo-600">分析时间</p>
                            <p class="font-medium text-indigo-900">${this.formatDateTime(data.created_at)}</p>
                        </div>
                    </div>
                </div>

                <!-- 三级分类体系 -->
                <div class="bg-green-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-green-800 mb-3">
                        <i class="fas fa-sitemap mr-2"></i>三级分类体系
                    </h4>
                    <div class="space-y-4">
                        <div class="bg-white rounded-lg p-3">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-green-700">一级分类</span>
                                <span class="px-2 py-1 bg-green-200 text-green-800 rounded-full text-xs">${data.tslx_yj || '未分类'}</span>
                            </div>
                            <p class="text-sm text-slate-600">判断依据：${data.tslx_yjyj || '无'}</p>
                        </div>
                        <div class="bg-white rounded-lg p-3">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-green-700">二级分类</span>
                                <div class="flex items-center space-x-2">
                                    <span class="px-2 py-1 bg-blue-200 text-blue-800 rounded-full text-xs">${data.tslx_rj || '未分类'}</span>
                                    <span class="text-sm font-medium text-blue-600">置信度: ${this.formatConfidence(data.level2_confidence)}</span>
                                </div>
                            </div>
                            <p class="text-sm text-slate-600">判断依据：${data.tslx_rjyj || '无'}</p>
                        </div>
                        <div class="bg-white rounded-lg p-3">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-green-700">三级分类</span>
                                <div class="flex items-center space-x-2">
                                    <span class="px-2 py-1 bg-purple-200 text-purple-800 rounded-full text-xs">${data.tslx_sj || '未分类'}</span>
                                    <span class="text-sm font-medium text-purple-600">置信度: ${this.formatConfidence(data.level3_confidence)}</span>
                                </div>
                            </div>
                            <p class="text-sm text-slate-600">判断依据：${data.tslx_sjyj || '无'}</p>
                        </div>
                    </div>
                </div>

                <!-- 置信度图表 -->
                <div class="bg-yellow-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-yellow-800 mb-3">
                        <i class="fas fa-chart-bar mr-2"></i>置信度分析
                    </h4>
                    <div id="confidenceChart" class="h-48 bg-yellow-100 rounded-lg flex items-center justify-center">
                        <div class="text-center">
                            <i class="fas fa-chart-bar text-2xl text-yellow-600 mb-2"></i>
                            <p class="text-yellow-700">置信度图表加载中...</p>
                        </div>
                    </div>
                </div>

                <!-- 信访内容 -->
                <div class="bg-purple-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-purple-800 mb-3">
                        <i class="fas fa-file-alt mr-2"></i>信访内容
                    </h4>
                    <div class="bg-white rounded-lg p-3 max-h-32 overflow-y-auto">
                        <p class="text-slate-700 whitespace-pre-wrap">${data.xfnr || '无内容'}</p>
                    </div>
                </div>

                <!-- 地址信息 -->
                <div class="bg-slate-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-slate-800 mb-3">
                        <i class="fas fa-map-marker-alt mr-2"></i>地址信息
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-slate-600">投诉对象</p>
                            <p class="font-medium text-slate-900">${data.dzxx_tsdx || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">投诉地址</p>
                            <p class="font-medium text-slate-900">${data.dzxx_tsdz || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">行政区</p>
                            <p class="font-medium text-slate-900">${data.dzxx_xzq || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">街道</p>
                            <p class="font-medium text-slate-900">${data.dzxx_jd || '未知'}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 加载置信度图表
        setTimeout(() => {
            this.loadConfidenceChart(data);
        }, 100);
    }

    /**
     * 渲染情感分析详情
     */
    renderSentimentDetail(data) {
        const content = document.getElementById('resultDetailContent');
        const keywords = data.keywords_list || [];

        content.innerHTML = `
            <!-- 基本信息 -->
            <div class="space-y-6">
                <div class="bg-pink-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-pink-800 mb-3">
                        <i class="fas fa-heart mr-2"></i>情感分析详情
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-pink-600">信访编号</p>
                            <p class="font-medium text-pink-900">${data.petition_record_id || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-pink-600">分析时间</p>
                            <p class="font-medium text-pink-900">${this.formatDateTime(data.created_at)}</p>
                        </div>
                    </div>
                </div>

                <!-- 情感类型 -->
                <div class="bg-red-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-red-800 mb-3">
                        <i class="fas fa-smile mr-2"></i>情感类型分析
                    </h4>
                    <div class="bg-white rounded-lg p-4">
                        <div class="flex items-center justify-between mb-3">
                            <span class="text-sm font-medium text-red-700">情感类型</span>
                            <span class="px-3 py-2 bg-red-200 text-red-800 rounded-full text-sm font-medium">${data.sentiment_level || '未知'}</span>
                        </div>
                        <div class="mt-3">
                            <p class="text-sm text-red-600 mb-2">判断理由</p>
                            <div class="bg-red-50 rounded-lg p-3">
                                <p class="text-slate-700 whitespace-pre-wrap">${data.qgfx_pdly || '无判断理由'}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 情感摘要 -->
                <div class="bg-blue-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-blue-800 mb-3">
                        <i class="fas fa-file-alt mr-2"></i>情感摘要
                    </h4>
                    <div class="bg-white rounded-lg p-4">
                        <p class="text-slate-700 whitespace-pre-wrap leading-relaxed">${data.qgfx_zy || '无摘要'}</p>
                    </div>
                </div>

                <!-- 关键词云 -->
                <div class="bg-green-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-green-800 mb-3">
                        <i class="fas fa-cloud mr-2"></i>关键词分析
                    </h4>
                    <div id="keywordCloud" class="bg-white rounded-lg p-4 min-h-32">
                        ${keywords.length > 0 ? `
                            <div class="flex flex-wrap gap-2">
                                ${keywords.map((keyword, index) => `
                                    <span class="px-3 py-1 bg-green-200 text-green-800 rounded-full text-sm font-medium
                                           hover:bg-green-300 transition-colors cursor-pointer"
                                          style="font-size: ${Math.max(0.8, 1.2 - index * 0.1)}rem">
                                        ${keyword}
                                    </span>
                                `).join('')}
                            </div>
                        ` : '<p class="text-slate-500 text-center py-4">暂无关键词</p>'}
                    </div>
                </div>

                <!-- 信访内容 -->
                <div class="bg-purple-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-purple-800 mb-3">
                        <i class="fas fa-file-alt mr-2"></i>原始信访内容
                    </h4>
                    <div class="bg-white rounded-lg p-3 max-h-32 overflow-y-auto">
                        <p class="text-slate-700 whitespace-pre-wrap">${data.xfnr || '无内容'}</p>
                    </div>
                </div>

                <!-- 地址信息 -->
                <div class="bg-slate-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-slate-800 mb-3">
                        <i class="fas fa-map-marker-alt mr-2"></i>地址信息
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-slate-600">投诉对象</p>
                            <p class="font-medium text-slate-900">${data.dzxx_tsdx || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">投诉地址</p>
                            <p class="font-medium text-slate-900">${data.dzxx_tsdz || '未知'}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 渲染规范性分析详情
     */
    renderComplianceDetail(data) {
        const content = document.getElementById('resultDetailContent');
        const isCompliant = data.is_compliant || false;
        const complianceStatus = data.compliance_status || '未分析';

        content.innerHTML = `
            <!-- 基本信息 -->
            <div class="space-y-6">
                <div class="bg-cyan-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-cyan-800 mb-3">
                        <i class="fas fa-check-circle mr-2"></i>规范性分析详情
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-cyan-600">信访编号</p>
                            <p class="font-medium text-cyan-900">${data.petition_record_id || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-cyan-600">分析时间</p>
                            <p class="font-medium text-cyan-900">${this.formatDateTime(data.created_at)}</p>
                        </div>
                    </div>
                </div>

                <!-- 合规性判断 -->
                <div class="bg-white rounded-lg p-4 border-2 ${isCompliant ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}">
                    <h4 class="text-lg font-semibold mb-3 ${isCompliant ? 'text-green-800' : 'text-red-800'}">
                        <i class="fas ${isCompliant ? 'fa-check-circle text-green-600' : 'fa-times-circle text-red-600'} mr-2"></i>
                        合规性判断
                    </h4>
                    <div class="flex items-center justify-between mb-4">
                        <span class="text-2xl font-bold ${isCompliant ? 'text-green-700' : 'text-red-700'}">${complianceStatus}</span>
                        <div class="px-4 py-2 rounded-full ${isCompliant ? 'bg-green-200 text-green-800' : 'bg-red-200 text-red-800'}">
                            <i class="fas ${isCompliant ? 'fa-thumbs-up' : 'fa-thumbs-down'} mr-2"></i>
                            ${isCompliant ? '合规' : '不合规'}
                        </div>
                    </div>
                    <div class="bg-white rounded-lg p-3">
                        <p class="text-sm font-medium ${isCompliant ? 'text-green-700' : 'text-red-700'} mb-2">判断理由</p>
                        <p class="text-slate-700 whitespace-pre-wrap">${data.gffx_pdly || '无判断理由'}</p>
                    </div>
                </div>

                <!-- 答复内容 -->
                <div class="bg-blue-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-blue-800 mb-3">
                        <i class="fas fa-reply mr-2"></i>答复内容
                    </h4>
                    <div class="bg-white rounded-lg p-4 max-h-40 overflow-y-auto">
                        <p class="text-slate-700 whitespace-pre-wrap leading-relaxed">${data.gffx_dfnr || '无答复内容'}</p>
                    </div>
                </div>

                <!-- 信访内容 -->
                <div class="bg-purple-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-purple-800 mb-3">
                        <i class="fas fa-file-alt mr-2"></i>信访内容
                    </h4>
                    <div class="bg-white rounded-lg p-3 max-h-32 overflow-y-auto">
                        <p class="text-slate-700 whitespace-pre-wrap">${data.xfnr || '无内容'}</p>
                    </div>
                </div>

                <!-- 处理单位 -->
                <div class="bg-yellow-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-yellow-800 mb-3">
                        <i class="fas fa-building mr-2"></i>处理单位信息
                    </h4>
                    <div class="bg-white rounded-lg p-4">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <p class="text-sm text-yellow-600">去向单位</p>
                                <p class="font-medium text-yellow-900">${data.ts_qxdw || '未知'}</p>
                            </div>
                            <div>
                                <p class="text-sm text-yellow-600">投诉对象</p>
                                <p class="font-medium text-yellow-900">${data.dzxx_tsdx || '未知'}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 地址信息 -->
                <div class="bg-slate-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-slate-800 mb-3">
                        <i class="fas fa-map-marker-alt mr-2"></i>地址信息
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-slate-600">投诉地址</p>
                            <p class="font-medium text-slate-900">${data.dzxx_tsdz || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-slate-600">行政区</p>
                            <p class="font-medium text-slate-900">${data.dzxx_xzq || '未知'}</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 渲染重复分析详情
     */
    renderDuplicateDetail(data) {
        const content = document.getElementById('resultDetailContent');

        content.innerHTML = `
            <!-- 基本信息 -->
            <div class="space-y-6">
                <div class="bg-orange-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-orange-800 mb-3">
                        <i class="fas fa-copy mr-2"></i>重复分析详情
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-orange-600">重复组编号</p>
                            <p class="font-medium text-orange-900">${data.cfbh || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-orange-600">信访编号</p>
                            <p class="font-medium text-orange-900">${data.xfxh || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-orange-600">任务ID</p>
                            <p class="font-medium text-orange-900">${data.task_id || '未知'}</p>
                        </div>
                        <div>
                            <p class="text-sm text-orange-600">分析时间</p>
                            <p class="font-medium text-orange-900">${this.formatDateTime(data.created_at)}</p>
                        </div>
                    </div>
                </div>

                <!-- 重复分析结果 -->
                <div class="bg-red-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-red-800 mb-3">
                        <i class="fas fa-exclamation-triangle mr-2"></i>重复性分析
                    </h4>
                    <div class="bg-white rounded-lg p-4">
                        <div class="flex items-center justify-center mb-4">
                            <div class="text-center">
                                <div class="w-16 h-16 bg-red-200 rounded-full flex items-center justify-center mx-auto mb-2">
                                    <i class="fas fa-copy text-2xl text-red-600"></i>
                                </div>
                                <p class="text-lg font-semibold text-red-700">检测到重复信访</p>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="bg-red-50 rounded-lg p-3">
                                <p class="text-sm text-red-600 mb-1">重复组编号</p>
                                <p class="font-medium text-red-900">${data.cfbh || '无'}</p>
                            </div>
                            <div class="bg-red-50 rounded-lg p-3">
                                <p class="text-sm text-red-600 mb-1">信访索引</p>
                                <p class="font-medium text-red-900">${data.xfxh || '无'}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 相关记录 -->
                <div class="bg-blue-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-blue-800 mb-3">
                        <i class="fas fa-link mr-2"></i>相关记录
                    </h4>
                    <div class="bg-white rounded-lg p-4">
                        <div class="text-center py-8">
                            <i class="fas fa-search text-3xl text-blue-400 mb-3"></i>
                            <p class="text-blue-600 mb-2">正在加载相关记录...</p>
                            <p class="text-sm text-blue-500">系统正在查找与该重复组相关的其他信访记录</p>
                        </div>
                    </div>
                </div>

                <!-- 重复分析说明 -->
                <div class="bg-green-50 rounded-lg p-4">
                    <h4 class="text-lg font-semibold text-green-800 mb-3">
                        <i class="fas fa-info-circle mr-2"></i>分析说明
                    </h4>
                    <div class="bg-white rounded-lg p-4">
                        <div class="space-y-3">
                            <div class="flex items-start space-x-3">
                                <i class="fas fa-check-circle text-green-600 mt-1"></i>
                                <div>
                                    <p class="font-medium text-green-800">重复检测</p>
                                    <p class="text-sm text-green-700">系统已检测到此信访内容与已有记录存在重复</p>
                                </div>
                            </div>
                            <div class="flex items-start space-x-3">
                                <i class="fas fa-users text-green-600 mt-1"></i>
                                <div>
                                    <p class="font-medium text-green-800">重复组管理</p>
                                    <p class="text-sm text-green-700">相同问题的信访被归类到同一重复组中，便于统一处理</p>
                                </div>
                            </div>
                            <div class="flex items-start space-x-3">
                                <i class="fas fa-chart-line text-green-600 mt-1"></i>
                                <div>
                                    <p class="font-medium text-green-800">统计分析</p>
                                    <p class="text-sm text-green-700">重复分析有助于识别高频问题和热点区域</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 异步加载相关记录
        setTimeout(() => {
            this.loadRelatedRecords(data.cfbh);
        }, 1000);
    }

    /**
     * 加载详情地图
     */
    loadDetailMap(lng, lat) {
        const mapContainer = document.getElementById('detailMap');
        if (!mapContainer) return;

        try {
            // 检查是否已加载Leaflet
            if (typeof L === 'undefined') {
                mapContainer.innerHTML = `
                    <div class="text-center">
                        <i class="fas fa-map-marked-alt text-2xl text-yellow-600 mb-2"></i>
                        <p class="text-yellow-700">地图组件未加载</p>
                        <p class="text-sm text-yellow-600">经度: ${lng}, 纬度: ${lat}</p>
                    </div>
                `;
                return;
            }

            // 创建地图
            const map = L.map('detailMap').setView([lat, lng], 15);

            // 添加地图图层
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);

            // 添加标记
            L.marker([lat, lng]).addTo(map)
                .bindPopup(`位置坐标<br>经度: ${lng}<br>纬度: ${lat}`)
                .openPopup();

        } catch (error) {
            console.error('加载地图失败:', error);
            mapContainer.innerHTML = `
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle text-2xl text-red-600 mb-2"></i>
                    <p class="text-red-700">地图加载失败</p>
                    <p class="text-sm text-red-600">经度: ${lng}, 纬度: ${lat}</p>
                </div>
            `;
        }
    }

    /**
     * 加载置信度图表
     */
    loadConfidenceChart(data) {
        const chartContainer = document.getElementById('confidenceChart');
        if (!chartContainer) return;

        try {
            // 检查是否已加载Chart.js
            if (typeof Chart === 'undefined') {
                chartContainer.innerHTML = `
                    <div class="text-center">
                        <i class="fas fa-chart-bar text-2xl text-yellow-600 mb-2"></i>
                        <p class="text-yellow-700">图表组件未加载</p>
                    </div>
                `;
                return;
            }

            const ctx = document.createElement('canvas');
            chartContainer.innerHTML = '';
            chartContainer.appendChild(ctx);

            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['二级分类', '三级分类'],
                    datasets: [{
                        label: '置信度',
                        data: [
                            (data.level2_confidence || 0) * 100,
                            (data.level3_confidence || 0) * 100
                        ],
                        backgroundColor: [
                            'rgba(59, 130, 246, 0.8)',
                            'rgba(147, 51, 234, 0.8)'
                        ],
                        borderColor: [
                            'rgba(59, 130, 246, 1)',
                            'rgba(147, 51, 234, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                callback: function(value) {
                                    return value + '%';
                                }
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.parsed.y.toFixed(1) + '%';
                                }
                            }
                        }
                    }
                }
            });

        } catch (error) {
            console.error('加载置信度图表失败:', error);
            chartContainer.innerHTML = `
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle text-2xl text-red-600 mb-2"></i>
                    <p class="text-red-700">图表加载失败</p>
                </div>
            `;
        }
    }

    /**
     * 加载相关记录
     */
    async loadRelatedRecords(duplicateGroupId) {
        try {
            // 这里可以调用API获取相关记录
            // 暂时显示模拟数据
            const relatedContainer = document.querySelector('#resultDetailContent .bg-blue-50 .bg-white');
            if (relatedContainer) {
                relatedContainer.innerHTML = `
                    <div class="text-center py-8">
                        <i class="fas fa-search text-3xl text-blue-400 mb-3"></i>
                        <p class="text-blue-600 mb-2">暂无相关记录</p>
                        <p class="text-sm text-blue-500">重复组编号: ${duplicateGroupId}</p>
                        <p class="text-sm text-slate-500 mt-2">相关记录功能开发中...</p>
                    </div>
                `;
            }
        } catch (error) {
            console.error('加载相关记录失败:', error);
        }
    }

    /**
     * 格式化置信度
     */
    formatConfidence(confidence) {
        if (confidence === null || confidence === undefined) return '0%';
        return Math.round(confidence * 100) + '%';
    }

    /**
     * 格式化日期时间
     */
    formatDateTime(dateTimeString) {
        if (!dateTimeString) return '未知';
        try {
            return new Date(dateTimeString).toLocaleString('zh-CN');
        } catch (error) {
            return '未知';
        }
    }

    /**
     * 关闭详情模态框
     */
    closeDetailModal() {
        const modal = document.getElementById('resultDetailModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');

        // 清空内容
        const content = document.getElementById('resultDetailContent');
        content.innerHTML = '';
    }
    
    /**
     * 改变页面大小
     */
    changePageSize(newSize) {
        console.log('changePageSize被调用，新大小:', newSize, '当前大小:', this.pageSize);

        if (newSize === this.pageSize) {
            console.log('页面大小未改变，直接返回');
            return;
        }

        // 验证新页面大小是否有效
        const validSizes = [5, 10, 15, 20, 30, 50, 100];
        if (!validSizes.includes(newSize)) {
            console.error('无效的页面大小:', newSize);
            return;
        }

        console.log(`页面大小从 ${this.pageSize} 更改为: ${newSize}条/页`);

        // 更新页面大小
        this.pageSize = newSize;
        this.currentPage = 1; // 重置到第一页
        this.cache.clear(); // 清空缓存

        // 立即重新加载数据
        console.log('开始重新加载数据...');
        this.loadResults().then(() => {
            console.log('数据重新加载完成');
        }).catch(error => {
            console.error('重新加载数据失败:', error);
        });

        // 更新页面大小选择器的显示值
        const pageSizeSelect = document.getElementById('pageSizeSelect');
        if (pageSizeSelect) {
            pageSizeSelect.value = newSize;
            console.log('页面大小选择器值已更新为:', newSize);
        }
    }

    /**
     * 刷新结果
     */
    refreshResults() {
        this.cache.clear();
        this.loadResults();
        this.loadDashboardStats();
    }
    
    /**
     * 导出结果
     */
    exportResults() {
        // 这里可以实现导出逻辑
        console.log('导出结果');
        alert('导出功能开发中...');
    }
    
    /**
     * 显示加载状态
     */
    showLoading(show) {
        this.isLoading = show;
        const loadingState = document.getElementById('resultsLoadingState');
        const tableArea = document.getElementById('resultsTableArea');
        
        if (show) {
            loadingState.classList.remove('hidden');
            tableArea.classList.add('hidden');
        } else {
            loadingState.classList.add('hidden');
        }
    }
    
    /**
     * 显示空状态
     */
    showEmptyState() {
        document.getElementById('resultsTableArea').classList.add('hidden');
        document.getElementById('resultsPagination').classList.add('hidden');
        document.getElementById('resultsEmptyState').classList.remove('hidden');
        
        // 更新空状态提示信息
        const emptyStateElement = document.getElementById('resultsEmptyState');
        const currentTabName = this.analysisTypes[this.currentTab]?.name || '当前分析类型';
        emptyStateElement.innerHTML = `
            <i class="fas fa-inbox text-4xl text-slate-300 mb-4"></i>
            <p class="text-slate-500 text-lg mb-2">暂无${currentTabName}数据</p>
            <p class="text-slate-400 text-sm">请先创建分析任务并执行分析</p>
        `;
    }
    
    /**
     * 显示错误信息
     */
    showError(message) {
        console.error('分析结果页面错误:', message);
        
        // 移除已存在的错误提示
        const existingError = document.querySelector('.analysis-error-toast');
        if (existingError) {
            existingError.remove();
        }
        
        // 创建更友好的错误提示
        const errorToast = document.createElement('div');
        errorToast.className = 'analysis-error-toast fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
        errorToast.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fas fa-exclamation-circle"></i>
                <span class="font-medium">操作失败</span>
                <span class="text-sm">${message}</span>
                <button class="ml-4 text-red-200 hover:text-white" onclick="this.closest('.analysis-error-toast').remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        document.body.appendChild(errorToast);
        
        // 显示动画
        setTimeout(() => {
            errorToast.classList.remove('translate-x-full');
        }, 100);
        
        // 5秒后自动移除
        setTimeout(() => {
            if (errorToast.parentNode) {
                errorToast.classList.add('translate-x-full');
                setTimeout(() => {
                    if (errorToast.parentNode) {
                        errorToast.parentNode.removeChild(errorToast);
                    }
                }, 300);
            }
        }, 5000);
    }
    
    /**
     * 显示成功信息
     */
    showSuccess(message) {
        console.log('分析结果页面成功:', message);
        
        // 移除已存在的成功提示
        const existingSuccess = document.querySelector('.analysis-success-toast');
        if (existingSuccess) {
            existingSuccess.remove();
        }
        
        // 创建成功提示
        const successToast = document.createElement('div');
        successToast.className = 'analysis-success-toast fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
        successToast.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fas fa-check-circle"></i>
                <span class="font-medium">操作成功</span>
                <span class="text-sm">${message}</span>
                <button class="ml-4 text-green-200 hover:text-white" onclick="this.closest('.analysis-success-toast').remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        document.body.appendChild(successToast);
        
        // 显示动画
        setTimeout(() => {
            successToast.classList.remove('translate-x-full');
        }, 100);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (successToast.parentNode) {
                successToast.classList.add('translate-x-full');
                setTimeout(() => {
                    if (successToast.parentNode) {
                        successToast.parentNode.removeChild(successToast);
                    }
                }, 300);
            }
        }, 3000);
    }
}

// 全局实例，供HTML调用
let analysisResultsManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM内容已加载，创建分析结果管理器...');
    analysisResultsManager = new AnalysisResultsManager();

    // 添加额外的样式确保函数
    window.ensureTruncateCellStyles = function() {
        setTimeout(() => {
            const truncateCells = document.querySelectorAll('#resultsTableArea td.truncate-cell');
            console.log(`找到 ${truncateCells.length} 个truncate-cell单元格`);

            truncateCells.forEach((cell, index) => {
                // 强制应用样式
                cell.style.cssText = `
                    white-space: normal !important;
                    word-wrap: break-word !important;
                    overflow-wrap: break-word !important;
                    width: 100% !important;
                    max-width: none !important;
                    display: block !important;
                    box-sizing: border-box !important;
                    min-width: 0 !important;
                    position: relative !important;
                    float: none !important;
                    clear: none !important;
                    margin: 0 !important;
                    padding: 12px 6px !important;
                    background-color: rgba(102, 126, 234, 0.05) !important;
                `;

                // 调试信息
                if (index < 3) { // 只打印前3个单元格的信息
                    console.log(`单元格 ${index + 1}:`, {
                        className: cell.className,
                        offsetWidth: cell.offsetWidth,
                        scrollWidth: cell.scrollWidth,
                        textContent: cell.textContent.substring(0, 50) + '...'
                    });
                }
            });
        }, 1000); // 延迟1秒确保DOM完全渲染
    };

    // 监听表格数据变化
    const originalRenderTableBody = analysisResultsManager.renderTableBody;
    if (originalRenderTableBody) {
        analysisResultsManager.renderTableBody = function(...args) {
            const result = originalRenderTableBody.apply(this, args);
            window.ensureTruncateCellStyles();
            return result;
        };
    }

    // 页面加载完成后也执行一次
    window.ensureTruncateCellStyles();
});